<template>
  <el-dialog
    modal-class="login-dialog"
    class="login-dialog"
    :close-on-click-modal="true"
    :modal-append-to-body="false"
    :show-close="false"
    @close="handleclose"
    @open="handleOpen"
  >
    <div class="main h100 flex-h flex-center">
      <div class="contain flex-v flex-center">
        <div class="logo">
          <el-image
            v-if="logo"
            :src="logo"
            fit="cover"
            @click="router.push('/')"
          />
        </div>
        <!-- <div class="header">{{ title }}</div> -->
        <div class="content">
          <!-- <div class="block">
            <el-input
              placeholder="账号"
              size="large"
              v-model="username"
              autocomplete="off"
              autofocus
              @keyup="handleKeyup"
            >
              <template #prefix>
                <el-icon>
                  <UserFilled />
                </el-icon>
              </template>
            </el-input>
          </div> -->
          <el-form :model="form" :rules="rules" ref="formEl" label-width="0">
            <el-form-item prop="mobile">
              <div class="block">
                <el-input
                  placeholder="手机号"
                  size="large"
                  v-model="form.mobile"
                  autocomplete="tel"
                  maxlength="11"
                  clearable
                  type="text"
                  autofocus
                  @keyup="handleKeyup"
                >
                  <template #prefix>
                    <el-icon>
                      <UserFilled />
                    </el-icon>
                  </template>
                </el-input>
              </div>
            </el-form-item>
            <el-form-item prop="code">
              <div class="block">
                <el-input
                  placeholder="手机验证码"
                  size="large"
                  v-model="form.code"
                  autocomplete="off"
                  @keyup="handleKeyup"
                >
                  <template #prefix>
                    <el-icon>
                      <Iphone />
                    </el-icon>
                  </template>
                  <template #append>
                    <span
                      v-if="mobileCodeTimer <= 0"
                      class="getMobileCode liner-btn"
                      style="cursor: pointer"
                      @click="getSmsCode"
                    >
                      获取验证码
                    </span>
                    <span v-if="mobileCodeTimer > 0" class="getMobileCode">
                      {{ mobileCodeTimer }}秒
                    </span>
                  </template>
                </el-input>
              </div>
            </el-form-item>
          </el-form>
          <!-- <div class="block">
            <el-input
              placeholder="密码"
              size="large"
              v-model="password"
              show-password
              autocomplete="off"
              @keyup="handleKeyup"
            >
              <template #prefix>
                <el-icon>
                  <Lock />
                </el-icon>
              </template>
            </el-input>
          </div> -->

          <el-row class="btn-row">
            <el-button
              class="login-btn w100 liner-btn liner-btn-opacity"
              size="large"
              type="primary"
              @click="login"
              >登录</el-button
            >
          </el-row>
          <!-- <div class="opt flex-h flex-between">
          <span @click="router.push('/register')">注册</span>
          <span @click="showResetPass = true">重置密码</span>
        </div> -->

          <div v-if="wechatLoginURL !== ''">
            <el-divider class="divider">其他登录方式</el-divider>

            <div class="clogin">
              <a class="wechat-login" :href="wechatLoginURL"
                ><i class="iconfont icon-wechat"></i
              ></a>
            </div>
          </div>
        </div>
        <!-- <div class="close-icon" @click="handleclose">
          <el-icon class="ft-22 cursor" style="color: #5b97ff;"><CircleClose /></el-icon>
        </div> -->
      </div>

      <!-- <reset-pass @hide="showResetPass = false" :show="showResetPass" />

      <footer-bar /> -->
    </div>
  </el-dialog>
</template>

<script setup>
import { onMounted, ref, reactive } from "vue";
import { CircleClose, UserFilled, Iphone } from "@element-plus/icons-vue";
import { httpGet, httpPost } from "@/utils/http";
import { useRouter } from "vue-router";
import FooterBar from "@/components/FooterBar.vue";
import { isMobile } from "@/utils/libs";
import { setUserToken } from "@/store/session";
import { showMessageError } from "@/utils/dialog";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
import {
  getTenantIdByName,
  sendSmsCode,
  smsLogin,
  getInfo,
  getUserMsg,
} from "@/api/login";
import { useUserStore } from "@/store/user";
import { useMessage } from "@/hooks/web/useMessage";
const setMessage = useMessage();
const userStore = useUserStore();
const router = useRouter();
const title = ref("Geek-AI");
const username = ref(import.meta.env.VITE_APP_USER);
const password = ref(import.meta.env.VITE_APP_PASS);
const form = reactive({
  mobile: import.meta.env.DEV ? '13000000000' : "",
  code: import.meta.env.DEV ? 123 : "",
});
const rules = {
  mobile: [
    {
      required: true,
      message: "请输入手机号",
      trigger: ["blur", "change"],
    },
    // { min: 11, message: "请输入正确手机号", trigger: "blur" },
  ],
  code: [
    {
      required: true,
      message: "请输入手机验证码",
      trigger: ["blur", "change"],
    },
  ],
};
const showResetPass = ref(false);
const logo = ref("http://ai.jiyundata.cn/jlntv/static/2024/12/18/logo (1).png");
const licenseConfig = ref({});
const wechatLoginURL = ref("");
const mobileCodeTimer = ref(0);
const getSmsCode = async () => {
  if (form.mobile.trim() === "") {
    return ElMessage.error("请输入手机号");
  }
  await sendSmsCode({ mobile: form.mobile, scene: 1 }).then(async () => {
    setMessage.success("发送成功!");
    // 设置倒计时
    mobileCodeTimer.value = 60;
    let msgTimer = setInterval(() => {
      mobileCodeTimer.value = mobileCodeTimer.value - 1;
      if (mobileCodeTimer.value <= 0) {
        clearInterval(msgTimer);
      }
    }, 1000);
  });
};
onMounted(() => {
  // 获取系统配置
});

const emits = defineEmits(["update:modelValue", "success", "loginCatch"]);
const handleclose = (params) => {
  console.log("关闭");
  emits("update:modelValue", false);
};
const handleKeyup = (e) => {
  if (e.key === "Enter") {
    login();
  }
};
const handleOpen = (params) => {
  formEl.value.clearValidate();
};

const validate = async (params) => {
  // if (form.mobile.trim() === "") {
  //   return;
  // }
  // if (form.code.trim() === "") {
  //   return ElMessage.error("请输入手机验证码");
  // }
};
const formEl = ref("");
const login = async () => {
  if (!formEl) return;
  await formEl.value.validate(async (valid, fields) => {
    if (valid) {
      console.log("submit!");

      await smsLogin({
        ...form,
      })
        .then(async (res) => {
          // setToken(res);
          setUserToken(res.accessToken);
          let info = await getInfo();
          userStore.setUser(info);
          getUserMsg().then((res) => {
            if (res.isShow) {
              ElMessage({
                message: res.message,
                duration: 0,
                type: "warning",
                showClose: true,
              });
            }
          });
          handleclose();
          emits("success");
          // }
          // push({ path: redirect.value || permissionStore.addRouters[0].path });
        })
        .catch((err) => {
          emits("loginCatch", err, form.mobile);
        })
        .finally(() => {
          // loginLoading.value = false;
          // setTimeout(() => {
          //   const loadingInstance = ElLoading.service();
          //   loadingInstance.close();
          // }, 400);
        });
    } else {
      console.log("error submit!", fields);
    }
  });
  // httpPost("/api/user/login", {
  //   username: username.value.trim(),
  //   password: password.value.trim(),
  // })
  //   .then((res) => {
  //     setUserToken(res.data.token);
  //     if (isMobile()) {
  //       router.push("/mobile");
  //     } else {
  //       router.push("/chat");
  //     }
  //   })
  //   .catch((e) => {
  //     showMessageError("登录失败，" + e.message);
  //   });
};
</script>

<style lang="stylus" scoped>
@import "../assets/css/login.styl"
  .getMobileCode{
    // background:var()
    box-shadow:none
    padding 0 10px
    width 90px
    text-align center
    }
    .block{
      width 100%
      :deep(.el-input-group__append){
        padding:0}
      }
</style>
